<!-- 完善个人信息 -->
<script setup lang="ts">
import { completeProfileAPI } from '@/apis/completeProfile'
import router from '@/router'
import { useGeneralDataStore } from '@/store/generalData'
import { useUserInfoStore } from '@/store/userInfo'

// 如果从班级详情等页面跳进来登录页面，则这个值不为空，则登录或完善信息后返回进来时的页面
const abnormal = ref('')

onLoad((options) => {
  if (options && options.abnormal)
    abnormal.value = options.abnormal
})

const userInfoStore = useUserInfoStore()
const generalDataStore = useGeneralDataStore()

// 表单数据
const formData = ref({
  username: '', // 姓名
  company: '', // 单位
  company_type: '', // 单位类型
  duties: '', // 职务
})

// 校验规则
const rules = {
  username: [
    { required: true, message: '姓名不可为空', trigger: ['blur', 'change'] },
  ],
  company: [
    { required: true, message: '单位不可为空', trigger: ['blur', 'change'] },
  ],
  company_type: [
    { required: true, message: '单位类型不可为空', trigger: ['blur', 'change'] },
  ],
  duties: [
    { required: true, message: '职务不可为空', trigger: ['blur', 'change'] },
  ],
}

// 表单组件 ref
const formRef = ref<any>(null)
// 是否处于加载中状态
const loading = ref(false)
// 是否显示提交成功弹窗
const isShowSuccessModal = ref(false)

/* ------------------------------ 选择单位类型 START ------------------------------ */
const selectedCompanyTypeIndex = ref(0)
const companyTypes = computed(() => {
  let val: string[] = []
  if (generalDataStore.generalData?.company_type) {
    Object.keys(generalDataStore.generalData?.company_type).forEach((key: string) => {
      val.push(generalDataStore.generalData?.company_type[key])
    })
  }
  else {
    val = ['省级单位', '市级单位', '区级单位']
  }
  return val
})

function handleSelectCompanyType(e: any) {
  const index = Number(e.detail.value) + 1
  if (generalDataStore.generalData?.company_type) {
    formData.value.company_type = generalDataStore.generalData?.company_type[index.toString()]
  }
  else {
    const types = ['省级单位', '市级单位', '区级单位']
    formData.value.company_type = types[e.detail.value]
  }
  selectedCompanyTypeIndex.value = e.detail.value
}
/* ------------------------------- 选择单位类型 END ------------------------------- */

/**
 * @description 提交表单时触发
 */
const handleSubmit = useThrottleFn(() => {
  if (userInfoStore.userInfo && userInfoStore.userInfo.token) {
    formRef.value.validate()
      .then(async () => {
        loading.value = true

        try {
          const res = await completeProfileAPI(
            formData.value,
            userInfoStore.userInfo!.token,
          )
          if (res.data?.code === 1) {
            userInfoStore.setUserInfo({
              ...userInfoStore.userInfo!,
              ...formData.value,
            })
            isShowSuccessModal.value = true
          }
          else { uni.showToast({ title: res.data?.msg, icon: 'none' }) }
        }
        catch (err) {
          uni.showToast({ title: JSON.stringify(err), icon: 'none' })
        }
      })
      .catch((errors: AnyObject[]) => {
        // 表单验证失败
        if (errors.length > 0)
          uni.showToast({ title: errors[0].message, icon: 'none' })
      })
  }
  else {
    uni.showToast({ title: '提交失败，请重试', icon: 'none' })
  }
}, 1000)

/**
 * @description 提交成功，退出页面
 */
function handleExit() {
  // 如果从班级详情等页面进来的登录，则完善信息后返回那个页面
  if (abnormal.value)
    router.back({ delta: 2, animationType: 'pop-out' })
  else
    router.replaceAll('home')
}
</script>

<template>
  <view class="min-h-screen bg-white">
    <!-- 表单 START -->
    <uv-form ref="formRef" :model="formData" :rules="rules">
      <Divider width="720" color="#E6E6E6" />
      <Spacer height="28" />
      <uv-form-item prop="username" :custom-style="{ padding: 0, margin: 0 }">
        <ListCell label="姓名">
          <ListInput v-model="formData.username" placeholder="请输入您的姓名" />
        </ListCell>
      </uv-form-item>
      <Divider width="700" color="#E6E6E6" />
      <uv-form-item prop="company" :custom-style="{ padding: 0, margin: 0 }">
        <ListCell label="单位">
          <ListInput v-model="formData.company" placeholder="请输入您的单位" />
        </ListCell>
      </uv-form-item>
      <Divider width="700" color="#E6E6E6" />
      <uv-form-item prop="company_type" :custom-style="{ padding: 0, margin: 0 }">
        <picker
          mode="selector" :value="selectedCompanyTypeIndex" :range="companyTypes || ['省级单位', '市级单位', '区级单位']"
          @change="handleSelectCompanyType"
        >
          <ListCell label="单位类型">
            <ListLink :value="formData.company_type" placeholder="请选择您的单位类型" />
          </ListCell>
        </picker>
      </uv-form-item>
      <Divider width="700" color="#E6E6E6" />
      <uv-form-item prop="duties" :custom-style="{ padding: 0, margin: 0 }">
        <ListCell label="职务">
          <ListInput v-model="formData.duties" placeholder="请输入您的职务" />
        </ListCell>
      </uv-form-item>
      <Divider width="700" color="#E6E6E6" />
      <button
        class="fixed bottom-80rpx h-100rpx w-650rpx flex items-center justify-center rounded-full bg-#0037AE text-30rpx text-white font-medium leading-30rpx x-center"
        hover-class="bg-#3266D9"
        @tap="handleSubmit"
      >
        提交
      </button>
    </uv-form>
    <!-- 表单 END -->
  </view>

  <uv-overlay :show="isShowSuccessModal" @tap="isShowSuccessModal = false">
    <uv-transition mode="zoom-in" :show="isShowSuccessModal">
      <view class="relative h-screen w-screen">
        <view class="absolute left-50% top-50% -translate-50%">
          <Dialog
            :show-cancel-button="false"
            title="提交成功"
            content=""
            confirm-label="确定"
            @cancel="isShowSuccessModal = false"
            @confirm="handleExit"
          />
        </view>
      </view>
    </uv-transition>
  </uv-overlay>
</template>

<route lang="yaml">
name: 'profileCompletion'
style:
  navigationBarTitleText: '完善信息'
layout: 'custom'
</route>
